package com.ruoyi.learn.java.jvm;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class MethodAreaOOMDemo {
    // JDK1.8及之后使用以下JVM参数:
    // -XX:MetaspaceSize=10M -XX:MaxMetaspaceSize=10M

    public static List<char[]>    bytes = new ArrayList<>();

    static {
        try {
            log.info("开始执行");
            for(int i = 0; i < 100000; i++){
                log.info("开始执行第{}次", i);
                bytes.add(new char[10 * 1024 * 1024]);
                Thread.sleep(500);
            }
            log.info("执行结束");
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws Exception {
        ClassPool pool = ClassPool.getDefault();
        int i = 0;

        try {
            while (true) {
//                bytes.add(new char[100 * 1024 * 1024]);
//                bytes = Arrays.copyOf(bytes, bytes.length);
                // 动态创建类
                CtClass ctClass = pool.makeClass("GeneratedClass" + i);

                // 添加方法
                CtMethod method = CtMethod.make(
                        "public void method" + i + "() { System.out.println(\"Hello from method" + i + "\"); }",
                        ctClass);
                ctClass.addMethod(method);

                // 加载类到JVM
                Class<?> clazz = ctClass.toClass();

                System.out.println("Generated and loaded class: " + clazz.getName());
                i++;
                Thread.sleep(1000);
            }
        } catch (Throwable e) {
            System.out.println("Generated " + i + " classes before error");
            System.out.println("Error: " + e);
        }
    }
}